<?php

namespace app\middleware;

use app\model\StationPrice;
use app\model\SupplierPriceRule;
use app\model\User;
use Closure;
use think\facade\Cache;

class ApiMiddleware
{
    public function handle(\think\Request $request, Closure $next)
    {
        $author = $request->header('authorization');
        $author = json_decode($author, true);
        if (!empty($author)) {
            $token = Cache::get('api_' . $author['token'] ?? '');
            if (!empty($token) && $token['verify_time'] > time()) {
                $use = app(
                    User::class
                )->where('id', $token['id'])->find();
                if (!empty($use)) $request->user = $use;
            }
        }
//        $defaultConf = @file_get_contents("./station_config/price.conf");
//        $defaultConf = json_decode(str_replace(["\r\n", "\n", "\t"], "", $defaultConf), true);
//        $request->configPrice = $defaultConf;
//        //获取默认油价折扣
//        $aps = app(SupplierPriceRule::class);
//        $def = $aps->where('supplier', 0)->where('state', 1)->where('start_time', '<=', date("Y-m-d H:i:s"))->where('end_time', '>=', date("Y-m-d H:i:s"))->find();
        if (!empty($use['supplier'])) {
            //获取特殊定价油站编号
            $sup_station = app(StationPrice::class)->whereIn('sup_id',[$use['supplier'],0])->column("station_id,discount_price,gun_price,office_price,oil_id,sup_id");
            if(!empty($sup_station)){
                $st = [];
                foreach ($sup_station as $v){
                    $st[$v['oil_id']][$v['sup_id']][$v['station_id']] = $v;
                }
                $request->supplierPrice = $st;
            }
        }
//        $request->supplierPrice = $sup ?? $def;
        return $next($request);
    }
}
